package com.zhehekeji.opsys.api.plugin.wechat.service;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBException;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zhehekeji.opsys.api.cache.WechatCache;
import com.zhehekeji.opsys.api.code.LuckyDrawResultCode;
import com.zhehekeji.opsys.api.common.util.DateFormatUtil;
import com.zhehekeji.opsys.api.enm.WinningResultStatus;
import com.zhehekeji.opsys.api.entity.TWechatConfig;
import com.zhehekeji.opsys.api.entity.TWechatRedpackRecord;
import com.zhehekeji.opsys.api.entity.TWechatToken;
import com.zhehekeji.opsys.api.entity.TWinningResult;
import com.zhehekeji.opsys.api.plugin.wechat.code.WechatResultCode;
import com.zhehekeji.opsys.api.plugin.wechat.enm.MsgType;
import com.zhehekeji.opsys.api.plugin.wechat.rsp.AccessTokenRsp;
import com.zhehekeji.opsys.api.plugin.wechat.rsp.CheckSignRsp;
import com.zhehekeji.opsys.api.plugin.wechat.rsp.QrcodeCreateRsp;
import com.zhehekeji.opsys.api.plugin.wechat.rsp.QrcodeShowRsp;
import com.zhehekeji.opsys.api.plugin.wechat.rsp.RedpackRsp;
import com.zhehekeji.opsys.api.plugin.wechat.rsp.TextRsp;
import com.zhehekeji.opsys.api.plugin.wechat.util.DESedeUtils;
import com.zhehekeji.opsys.api.plugin.wechat.util.FileUtils;
import com.zhehekeji.opsys.api.plugin.wechat.util.HttpUtils;
import com.zhehekeji.opsys.api.plugin.wechat.util.SignUtils;
import com.zhehekeji.opsys.api.plugin.wechat.util.XmlUtils;
import com.zhehekeji.opsys.api.resp.LuckyDrawResp;
import com.zhehekeji.opsys.api.service.CommonService;
import com.zhehekeji.opsys.api.service.manager.ActivityManagerService;
import com.zhehekeji.opsys.api.service.manager.UserManagerService;
import com.zhehekeji.opsys.api.service.validate.ActivityValidate;
import com.zhehekeji.opsys.api.util.UUIDUtils;

import net.sf.json.JSONObject;

/**
 * @ClassName WechatManagerService
 * @Description TODO
 * @author chenweiliu chenwei.liu@163.com
 * @date 2018-1-3   上午11:17:55
 */
@Service
public class WechatManagerService extends CommonService{
	
	private static final Logger logger = LoggerFactory.getLogger(WechatManagerService.class);
	
	@Autowired
	private WechatCache wechatCache;
	@Autowired
	private ActivityValidate activityValidate;
	@Autowired
	private UserManagerService userManagerService;
	@Autowired
	private ActivityManagerService activityMangerService;
	
	private static synchronized String buildBillno(String mchid){
		String billno;
		String timeStr = DateFormatUtil.format(new Date(), "yyyyMMddHHmmssSSS");
		if (StringUtils.isBlank(mchid)){
			billno = timeStr;
		}else{
			billno = mchid + timeStr;
		}
		int dif = billno.length() - 28;
		if (dif == 0){
			return billno;
		}else if (dif > 0){
			billno = billno.substring(0, 28);
		}else{
			dif = -dif;
			for (int i=0 ; i<dif; i++){
				billno = billno + RandomUtils.nextInt(9);
			}
		}
		return billno;
	}
	
	public RedpackRsp send(String reOpenid, int totalAmount, int totalNum){
		//最高金额200元
		if (totalAmount > 20000){
			totalAmount = 20000;
		}
		RedpackRsp rsp = new RedpackRsp();
		try{
			TWechatConfig twechatConfig = wechatCache.getWechatConfig();
			if (twechatConfig == null){
				rsp.setReturnCode(RedpackRsp.Result.RETURN_FAIL);
				return rsp;
			}
			String nonceStr = UUIDUtils.randomUUID();
			String cert = twechatConfig.getMchCert();
			String mchid = twechatConfig.getMchId();
			String wxappid = twechatConfig.getAppId();
			String sendName = twechatConfig.getMchName();
			String clientip = twechatConfig.getClientIp();
			String key = twechatConfig.getMchKey();
			String url = twechatConfig.getRedpackUrl();
			String wishing = twechatConfig.getRedpackWishing();
			String actName = twechatConfig.getRedpackActName();
			String remark = twechatConfig.getRedpackRemark();
			String billno = buildBillno(mchid);
			String sign = SignUtils.redpackSign(nonceStr, billno, mchid, wxappid, sendName, reOpenid, totalAmount, totalNum, wishing, clientip, actName, remark, null, key);
			StringBuilder paramBuilder = new StringBuilder();
			paramBuilder.append("<xml>")
			.append("<sign>").append("<![CDATA[").append(sign).append("]]>").append("</sign>")
			.append("<mch_billno>").append("<![CDATA[").append(billno).append("]]>").append("</mch_billno>")
			.append("<mch_id>").append("<![CDATA[").append(mchid).append("]]>").append("</mch_id>")
			.append("<wxappid>").append("<![CDATA[").append(wxappid).append("]]>").append("</wxappid>")
			.append("<send_name>").append("<![CDATA[").append(sendName).append("]]>").append("</send_name>")
			.append("<re_openid>").append("<![CDATA[").append(reOpenid).append("]]>").append("</re_openid>")
			.append("<total_amount>").append("<![CDATA[").append(totalAmount).append("]]>").append("</total_amount>")
			.append("<total_num>").append("<![CDATA[").append(totalNum).append("]]>").append("</total_num>")
			.append("<wishing>").append("<![CDATA[").append(wishing).append("]]>").append("</wishing>")
			.append("<client_ip>").append("<![CDATA[").append(clientip).append("]]>").append("</client_ip>")
			.append("<act_name>").append("<![CDATA[").append(actName).append("]]>").append("</act_name>")
			.append("<remark>").append("<![CDATA[").append(remark).append("]]>").append("</remark>")
			/*.append("<scene_id>").append("<![CDATA[").append(sceneid).append("]]>").append("</scene_id>")*/
			.append("<nonce_str>").append("<![CDATA[").append(nonceStr).append("]]>").append("</nonce_str>")
			.append("</xml>");
			
			String param = paramBuilder.toString();
			logger.debug(param);
			String rspBody = HttpUtils.postFormSSL(url, param, cert, mchid);
			if (!StringUtils.isBlank(rspBody)){
				rsp = (RedpackRsp) XmlUtils.xmlToObject(rspBody, RedpackRsp.class);
			}
		}catch (Exception e){
			if (rsp == null){
				rsp = new RedpackRsp();
				rsp.setReturnCode(RedpackRsp.Result.RETURN_FAIL);
			}else{
				String returnCode = rsp.getReturnCode();
				if (StringUtils.isBlank(returnCode)){
					rsp.setReturnCode(RedpackRsp.Result.RETURN_FAIL);
				}
			}
			logger.error(e.getMessage(), e);
		}
		return rsp;
	}
	
	public AccessTokenRsp getAccessToken(){
		AccessTokenRsp rsp = new AccessTokenRsp();
		String resultDesc = "获取访问令牌成功！";
		try{
			TWechatToken tmpTWechatToken = entityDao.get(TWechatToken.class, null, null);
			if (tmpTWechatToken == null || StringUtils.isBlank(tmpTWechatToken.getAccessToken())){
				resultDesc = "获取访问令牌失败，数据不存在！";
				logger.error(resultDesc);
				rsp.setResultCode(WechatResultCode.ACCESS_TOKEN_DOES_NOT_EXIST);
				rsp.setResultDesc(resultDesc);
				return rsp;
			}
			rsp.setAccessToken(tmpTWechatToken.getAccessToken());
			rsp.setExpiresIn(tmpTWechatToken.getExpiresIn());
			logger.info(resultDesc);
		}catch (Exception e){
			resultDesc = "获取访问令牌失败，程序异常！";
			logger.error(resultDesc, e);
			rsp.setResultCode(WechatResultCode.APPLICATION_EXCEPTION);
			rsp.setResultDesc(resultDesc);
		}
		return rsp;
	}
	
	public QrcodeShowRsp getSafeQrcodeShow(String sign){
		QrcodeShowRsp rsp = new QrcodeShowRsp();
		String resultDesc = "获取二维码成功！";
		try{
			CheckSignRsp tmpCheckSignRsp = checkSign(sign);
			boolean checkFlag = tmpCheckSignRsp.isFlag();
			if (!checkFlag){
				rsp.setResultCode(WechatResultCode.PARAMETER_IS_NOT_LEGAL);
				rsp.setResultDesc("获取二维码失败，签名非法！");
				return rsp;
			}
			TWechatConfig tmpTWechatConfig = checkWechatConfig(rsp);
			if (rsp.getResultCode() != WechatResultCode.SUCCESS){
				return rsp;
			}
			TWechatToken tmpTWechatToken = checkWechatToken(rsp);
			if (rsp.getResultCode() != WechatResultCode.SUCCESS){
				return rsp;
			}
			getWechaturl(sign, tmpTWechatConfig, tmpTWechatToken, rsp, tmpCheckSignRsp.getUserID());
			if (rsp.getResultCode() != WechatResultCode.SUCCESS){
				return rsp;
			}
			logger.info(resultDesc);
		}catch (Exception e){
			resultDesc = "获取二维码失败，程序异常！";
			logger.error(resultDesc, e);
			rsp.setResultCode(WechatResultCode.APPLICATION_EXCEPTION);
			rsp.setResultDesc(resultDesc);
		}
		return rsp;
	}
	
	private TWechatConfig checkWechatConfig(QrcodeShowRsp rsp) throws SQLException{
		TWechatConfig tmpTWechatConfig = wechatCache.getWechatConfig();
		String resultDesc = "获取二维码成功！";
		if (tmpTWechatConfig == null){
			resultDesc = "获取二维码失败，微信配置不存在！";
			logger.error(resultDesc);
			rsp.setResultCode(WechatResultCode.WECHAT_CONFIG_DOES_NOT_EXIST);
			rsp.setResultDesc(resultDesc);
			return tmpTWechatConfig;
		}
		String tmpQrcodeCreateUrl = tmpTWechatConfig.getQrcodeCreateUrl();
		if (StringUtils.isBlank(tmpQrcodeCreateUrl)){
			resultDesc = "获取二维码失败，二维码生成调用Url为空！";
			logger.error(resultDesc);	
			rsp.setResultCode(WechatResultCode.QRCODE_CREATE_URL_DOES_NOT_EXIST);
			rsp.setResultDesc(resultDesc);
			return tmpTWechatConfig;
		}
		String tmpQrcodeShowUrl = tmpTWechatConfig.getQrcodeShowUrl();
		if (StringUtils.isBlank(tmpQrcodeShowUrl)){
			resultDesc = "获取二维码失败，二维码生成呈现Url为空！";
			logger.error(resultDesc);	
			rsp.setResultCode(WechatResultCode.QRCODE_SHOW_URL_DOES_NOT_EXIST);
			rsp.setResultDesc(resultDesc);
			return tmpTWechatConfig;
		}
		String tmpQrcodePicStoreDir = tmpTWechatConfig.getQrcodePicStoreDir();
		if (StringUtils.isBlank(tmpQrcodePicStoreDir)){
			resultDesc = "获取二维码失败，图片存储路径不存在！";
			logger.error(resultDesc);
			rsp.setResultCode(WechatResultCode.QRCODE_STORE_DIR_DOES_NOT_EXIST);
			rsp.setResultDesc(resultDesc);
			return tmpTWechatConfig;
		}
		String tmpQrcodePicHttpPath = tmpTWechatConfig.getQrcodePicHttpPath();
		if (StringUtils.isBlank(tmpQrcodePicHttpPath)){
			resultDesc = "获取二维码失败，图片访问路径不存在！";
			logger.error(resultDesc);
			rsp.setResultCode(WechatResultCode.QRCODE_HTTP_PATH_DOES_NOT_EXIST);
			rsp.setResultDesc(resultDesc);
			return tmpTWechatConfig;
		}
		return tmpTWechatConfig;
	}
	
	private TWechatToken checkWechatToken(QrcodeShowRsp rsp) throws SQLException{
		TWechatToken tmpTWechatToken = entityDao.get(TWechatToken.class, null, null);
		if (tmpTWechatToken == null || StringUtils.isBlank(tmpTWechatToken.getAccessToken())){
			logger.error("获取二维码失败，访问令牌不存在！");
			rsp.setResultCode(WechatResultCode.ACCESS_TOKEN_DOES_NOT_EXIST);
			rsp.setResultDesc("获取二维码失败，访问令牌不存在！");
		}
		return tmpTWechatToken;
	}
	
	public CheckSignRsp checkSign(String sign) throws SQLException{
		CheckSignRsp rsp = new CheckSignRsp();
		rsp.setFlag(true);
		if (StringUtils.isBlank(sign)){
			logger.error("签名非法！");
			rsp.setFlag(false);
			return rsp;
		}
		TWechatConfig tmpTWechatConfig = wechatCache.getWechatConfig();
		if (tmpTWechatConfig == null){
			logger.error("微信配置不存在！");
			rsp.setFlag(false);
			return rsp;
		}
		String tmpQrcodePicSignKey = tmpTWechatConfig.getQrcodePicSignKey();
		if (StringUtils.isBlank(tmpQrcodePicSignKey)){
			logger.error("二维码签名key不存在！");	
			rsp.setFlag(false);
			return rsp;
		}
		String tmpPlaintext;
		try{
			tmpPlaintext = DESedeUtils.decrypt(sign, tmpQrcodePicSignKey);
		}catch (Exception e){
			logger.error("签名非法！", e);
			rsp.setFlag(false);
			return rsp;
		}
		String[] tmpArrayDecrypt = tmpPlaintext.split("\\&");
		if (tmpArrayDecrypt.length != 5){
			logger.error("签名参数长度不等于5！");
			rsp.setFlag(false);
			return rsp;
		}
		String[] tmpArrayParam;
		Map<String, String> tmpMap = new HashMap<String, String>();
		for (String tmpStr : tmpArrayDecrypt){
			if (StringUtils.isBlank(tmpStr)){
				logger.error("签名参数不能为空！");
				rsp.setFlag(false);
				return rsp;
			}
			tmpArrayParam = tmpStr.split("=");
			if (tmpArrayParam == null || tmpArrayParam.length != 2){
				logger.error("签名参数不满足k=v格式");
				rsp.setFlag(false);
				return rsp;
			}
			tmpMap.put(tmpArrayParam[0], tmpArrayParam[1]);
		}
		String tmpKey = tmpMap.get("key");
		String tmpActivityCode = tmpMap.get("activityCode");
		String tmpUserID = tmpMap.get("userID");
		String tmpStrLimitWinNum = tmpMap.get("limitWinNum");
		String tmpTimestamp = tmpMap.get("timestamp");
		if (StringUtils.isBlank(tmpKey)){
			logger.error("签名密钥为空！");
			rsp.setFlag(false);
			return rsp;
		}
		if (StringUtils.isBlank(tmpActivityCode)){
			logger.error("签名参数[activityCode]为空！");
			rsp.setFlag(false);
			return rsp;
		}
		if (StringUtils.isBlank(tmpUserID)){
			logger.error("签名参数[userID]为空！");
			rsp.setFlag(false);
			return rsp;
		}
		if (StringUtils.isBlank(tmpStrLimitWinNum)){
			logger.error("签名参数[limitWinNum]为空！");
			rsp.setFlag(false);
			return rsp;
		}
		int tmpLimitWinNum;
		try{
			tmpLimitWinNum = Integer.parseInt(tmpStrLimitWinNum);
		}catch (Exception e){
			logger.error("签名参数[limitWinNum]类必须为int型！");
			rsp.setFlag(false);
			return rsp;
		}		
		if (tmpLimitWinNum < 0 ){
			logger.error("签名参数[limitWinNum]必须大于等于0！");
			rsp.setFlag(false);
			return rsp;
		}
		if (StringUtils.isBlank(tmpTimestamp)){
			logger.error("签名参数[timestamp]为空！");
			rsp.setFlag(false);
			return rsp;
		}
		if (!tmpKey.equals(tmpQrcodePicSignKey)){
			logger.error("签名参数[key]错误！");
			rsp.setFlag(false);
			return rsp;
		}
		long tmpLong;
		try{
			tmpLong = Long.parseLong(tmpTimestamp);
		}catch (NumberFormatException e){
			logger.error("签名参数[timestamp]类必须为long型！");
			rsp.setFlag(false);
			return rsp;
		}
		Long tmpSignEffectiveTime = tmpTWechatConfig.getQrcodePicSignEffectiveTime();
		if (tmpSignEffectiveTime == null || tmpSignEffectiveTime < 0){
			tmpSignEffectiveTime = 0L;
		}
		if (tmpSignEffectiveTime > 0){
			long tmpLongCur = System.currentTimeMillis();
			long tmpDiv = tmpLongCur - tmpLong;
			if (tmpDiv < 0) tmpDiv = - tmpDiv;
			if (tmpDiv > tmpSignEffectiveTime){
				logger.error("签名已过期！");
				rsp.setFlag(false);
				return rsp;
			}
		}
		rsp.setActivityCode(tmpActivityCode);
		rsp.setUserID(tmpUserID);
		rsp.setLimitWinNum(tmpLimitWinNum);
		return rsp;
	}
	
	//@Transactional
	public QrcodeShowRsp getQrcodeShow(String activityCode, String userID, int limitWinNum){
		QrcodeShowRsp rsp = new QrcodeShowRsp();
		String resultDesc = "获取二维码成功！";
		if (StringUtils.isBlank(activityCode)){
			resultDesc = "获取二维码失败，活动编码非法！";
			logger.error(resultDesc);
			rsp.setResultCode(WechatResultCode.PARAMETER_IS_NOT_LEGAL);
			rsp.setResultDesc(resultDesc);
			return rsp;
		}
		if (StringUtils.isBlank(userID)){
			resultDesc = "获取二维码失败，用户账号非法！";
			logger.error(resultDesc);
			rsp.setResultCode(WechatResultCode.PARAMETER_IS_NOT_LEGAL);
			rsp.setResultDesc(resultDesc);
			return rsp;
		}
		if (limitWinNum < 0) {
			limitWinNum = 0;
		}
		try{
			TWechatConfig tmpTWechatConfig = checkWechatConfig(rsp);
			if (rsp.getResultCode() != WechatResultCode.SUCCESS){
				return rsp;
			}
			TWechatToken tmpTWechatToken = checkWechatToken(rsp);
			if (rsp.getResultCode() != WechatResultCode.SUCCESS){
				return rsp;
			}
			String scene = activityCode + "$" + userID + "$" + limitWinNum;
			getWechaturl(scene, tmpTWechatConfig, tmpTWechatToken, rsp, userID);
			if (rsp.getResultCode() != WechatResultCode.SUCCESS){
				return rsp;
			}
			logger.info(resultDesc);
		}catch (Exception e){
			resultDesc = "获取二维码失败，程序异常！";
			logger.error(resultDesc, e);
			rsp.setResultCode(WechatResultCode.APPLICATION_EXCEPTION);
			rsp.setResultDesc(resultDesc);
		}
		return rsp;
	}
	
	private void getWechaturl(String scene, TWechatConfig twechatConfig, TWechatToken twechatToken, QrcodeShowRsp rsp, String userID){
		String tmpQrcodeCreateUrl = twechatConfig.getQrcodeCreateUrl() + "?access_token=" + twechatToken.getAccessToken();
		String param = "{\"expire_seconds\": " + twechatConfig.getQrcodeExpire() + ",\"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"" + scene + "\"}}}";
		String resultDesc;
		String rspBody = null;
		try {
			rspBody = HttpUtils.postJson(tmpQrcodeCreateUrl, param);
		} catch (IOException e) {
			resultDesc = "获取二维码失败，二维码生成调用失败！";
			logger.error(resultDesc, e);	
			rsp.setResultCode(WechatResultCode.QRCODE_CREATE_FAIL);
			rsp.setResultDesc(resultDesc);
			return;
		}
		if (StringUtils.isBlank(rspBody)){
			resultDesc = "获取二维码失败，二维码生成失败！";
			logger.error(resultDesc);	
			rsp.setResultCode(WechatResultCode.QRCODE_CREATE_FAIL);
			rsp.setResultDesc(resultDesc);
			return;
		}
		QrcodeCreateRsp tmpQrcodeCreateRsp = (QrcodeCreateRsp) JSONObject.toBean(JSONObject.fromObject(rspBody), QrcodeCreateRsp.class);
		String tmpTicket = tmpQrcodeCreateRsp.getTicket();
		if (StringUtils.isBlank(tmpTicket)){
			resultDesc = "获取二维码失败，二维码生成失败，ticket为空！";
			logger.error(tmpQrcodeCreateRsp.toString());
			logger.error(resultDesc);	
			rsp.setResultCode(WechatResultCode.QRCODE_CREATE_FAIL);
			rsp.setResultDesc(resultDesc);
			return;
		}
		String tmpQrcodeShowUrl = twechatConfig.getQrcodeShowUrl() + "?ticket=" + tmpTicket;
		String fileRelativeDir = "1001" + File.separator + "wechatqrcode";
		String fileName = UUIDUtils.randomUUID() + ".jpg";
		String fileStoreDir = twechatConfig.getQrcodePicStoreDir() + File.separator + fileRelativeDir;
		File file = new File(fileStoreDir);
		if (!file.exists()){
			file.mkdirs();
		}
		String destPath = fileStoreDir + File.separator + fileName;
		try {
			FileUtils.download(tmpQrcodeShowUrl, destPath);
		} catch (Exception e) {
			resultDesc = "获取二维码失败，二维码本地存储失败！";
			logger.error(resultDesc, e);	
			rsp.setResultCode(WechatResultCode.QRCODE_CREATE_FAIL);
			rsp.setResultDesc(resultDesc);
			return;
		}
		//注册用户
		userManagerService.register(userID, null, null, 1001L);
		String tmpQrcode = fileRelativeDir + File.separator + fileName;
		String httpPath = twechatConfig.getQrcodePicHttpPath() + File.separator + tmpQrcode;
		rsp.setUrl(httpPath);
		rsp.setContent(tmpQrcodeCreateRsp.getUrl());
	}
	
	@Transactional
	public String handler(String msgType, String event, String eventKey, String toUserName, String fromUserName){
		String rspStr = StringUtils.EMPTY;
		try{
			TWechatConfig tmpTWechatConfig = wechatCache.getWechatConfig();
			if (tmpTWechatConfig == null){
				return rspStr;
			}
			String activityCode;
			String userID;
			int limitWinNum;
			String tmpQrcodePicSignKey = tmpTWechatConfig.getQrcodePicSignKey();
			if (StringUtils.isBlank(tmpQrcodePicSignKey)){
				String[] scene = eventKey.split("\\$");
				if (scene == null || scene.length != 3){
					return rspStr;
				}
				activityCode = scene[0];
				userID = scene[1];
				limitWinNum = NumberUtils.toInt(scene[2]);
			}else{
				CheckSignRsp tmpCheckSignRsp = checkSign(eventKey);
				if (!tmpCheckSignRsp.isFlag()){
					return rspStr;
				}else{
					activityCode = tmpCheckSignRsp.getActivityCode();
					userID = tmpCheckSignRsp.getUserID();
					limitWinNum = tmpCheckSignRsp.getLimitWinNum();
				}
			}
			if (limitWinNum < 0) {
				limitWinNum = 0;
			}
			//注册用户
			//userManagerService.register(userID, null, null, 1001L);
			TextRsp tmpTextRsp = new TextRsp();
			tmpTextRsp.setCreateTime(System.currentTimeMillis());
			tmpTextRsp.setFromUserName(toUserName);
			tmpTextRsp.setToUserName(fromUserName);
			tmpTextRsp.setMsgType(MsgType.TEXT.getType());
			tmpTextRsp.setContent("谢谢参与！");
			try {
				rspStr = XmlUtils.ObjectToXml(tmpTextRsp);
			} catch (JAXBException e) {
				logger.error("对象转xml失败", e);
			}
			//调用活动抽奖接口（随机派发红包）
			LuckyDrawResp rsp = activityMangerService.luckyDraw(activityCode, userID, limitWinNum);
			if (rsp.getResultCode() != LuckyDrawResultCode.SUCCESS){
				return rspStr;
			}
			Long tmpWinningResultId = rsp.getWinningResultId();
			if (tmpWinningResultId == null){
				return rspStr;
			}
			//单位元
			Integer price = rsp.getPrizePrice();
			if (price == null || price <= 0){
				return rspStr;
			}
			//换算为分
			price = price * 100;
			RedpackRsp redpackRsp = send(fromUserName, price, 1);
			logger.info(redpackRsp.toString());
			if (redpackRsp != null && redpackRsp.getReturnCode() != null && redpackRsp.getReturnCode().equals("SUCCESS") &&
					redpackRsp.getResultCode() != null && redpackRsp.getResultCode().equals("SUCCESS")){
				//发送成功
				TWinningResult tmpTWinningResult = entityDao.get(TWinningResult.class, tmpWinningResultId);
				if (tmpTWinningResult != null) {
					tmpTWinningResult.setStatus(WinningResultStatus.HAVA_SEND.getStatus());
					entityDao.update(tmpTWinningResult);
				}
				//发送成功
				TWechatRedpackRecord tmpRecord = new TWechatRedpackRecord();
				tmpRecord.setAccount(userID);
				tmpRecord.setAmount(price);
				tmpRecord.setCreateTime(new Date());
				tmpRecord.setOpenid(fromUserName);
				tmpRecord.setActivityCode(activityCode);
				entityDao.saveVoid(tmpRecord);
				return StringUtils.EMPTY;
			}
		}catch (Exception e){
			logger.error("处理消息失败", e);
		}
		return rspStr;
	}
}

